package com.beagle.njddapp.ui.activity.dirver;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.services.core.PoiItem;
import com.beagle.njddapp.R;
import com.beagle.njddapp.base.BaseMvpActivity;
import com.beagle.njddapp.bean.dirver.OilOrderState;
import com.beagle.njddapp.bean.owner.DIrverOrderBean;
import com.beagle.njddapp.bean.owner.NjBean;
import com.beagle.njddapp.core.UserService;
import com.beagle.njddapp.event.GiveBackEvent;
import com.beagle.njddapp.event.JieDanEvent;
import com.beagle.njddapp.ui.activity.ChooseAeraActivity;
import com.beagle.njddapp.ui.fragment.CommonMapfragment;
import com.beagle.njddapp.ui.presenter.DirverDetailPresenter;
import com.beagle.njddapp.ui.view.DirverDetailView;
import com.beagle.njddapp.utils.StatusBarUtil;
import com.beagle.njddapp.weight.dialog.JiayouDIalog;
import com.blankj.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Handler;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author hxx
 * @date 2021-03-21 13:32
 * 农机驾驶员-首页-订单详情
 */
public class DirverOrderDetailActivity extends BaseMvpActivity<DirverDetailView, DirverDetailPresenter> implements DirverDetailView, JiayouDIalog.JiaYouDialogHandleCallback {


    @BindView(R.id.commom_title_tv)
    TextView tvTitle;
    @BindView(R.id.common_container)
    RelativeLayout container;
    private DIrverOrderBean data;
    private DIrverOrderBean orderBean;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_owner)
    TextView tvOwner;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_caozuo)
    TextView tvCz;
    @BindView(R.id.rl_worktype)
    RelativeLayout rlWorkType;
    @BindView(R.id.tv_worktype)
    TextView tvWorkType;
    @BindView(R.id.rl_endtime)
    RelativeLayout rlendtime;
    @BindView(R.id.tv_endtime)
    TextView tvendTime;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_owner_phone)
    TextView tvPhone;
    @BindView(R.id.tv_tz)
    TextView tcTz;
    @BindView(R.id.prograssBar)
    ProgressBar progressBar;
    @BindView(R.id.iv_next)
    ImageView ivNext;
    @BindView(R.id.rl_resean)
    RelativeLayout rlReason;
    @BindView(R.id.ed_reason)
    EditText edReason;
    @BindView(R.id.rl_owner)
    RelativeLayout rlOwner;
    private JiayouDIalog jiayouDIalog;
    private String lastStr;
    private String lastTime="";
    private PoiItem currentPos;


    @Override
    public int getLayoutId() {
        return R.layout.activity_diver_order_detail;
    }

    @Override
    public void init() {
        StatusBarUtil.immersive(this, Color.WHITE);
        StatusBarUtil.darkMode(this);
        tvTitle.setText("订单详情");
        container.setBackgroundColor(Color.WHITE);
        int type = getIntent().getIntExtra("type", -1);
        if (type == 1) {
            data = (DIrverOrderBean) getIntent().getSerializableExtra("data");
        } else {
            orderBean = (DIrverOrderBean) getIntent().getSerializableExtra("data");
        }
        if (data != null) {
            tvType.setText(data.getMeshTypeName());
            tvOwner.setText(data.getMeshUserName());
            tvPhone.setText(data.getMeshUserPhone());
            tvNumber.setText(data.getMeshNum());
            tvWorkType.setText(data.getWorkTypeName());
            tvendTime.setText(data.getEndDate());
            if (0 == data.getOrderStatus()) {
                tvCz.setText("已取消");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
            } else if (1 == data.getOrderStatus()) {
                tvCz.setText("立即接单");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
//                rlUser.setVisibility(View.GONE);
//                rlWorkType.setVisibility(View.VISIBLE);
//                rlendtime.setVisibility(View.VISIBLE);
            } else if (2 == data.getOrderStatus()) {
                tvCz.setText("待移交");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
//                tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
//                rlUser.setVisibility(View.VISIBLE);
//                rlWorkType.setVisibility(View.GONE);
//                rlendtime.setVisibility(View.GONE);
            } else if (3 == data.getOrderStatus()) {
                tvCz.setText("确认");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_dirver_3));
//                tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
//                rlUser.setVisibility(View.VISIBLE);
//                rlWorkType.setVisibility(View.GONE);
//                rlendtime.setVisibility(View.GONE);
            } else if (4 == data.getOrderStatus()) {
                presenter.meshState(data);
                tvCz.setText("申请加油");
                tcTz.setText("调整");
                tcTz.setVisibility(View.VISIBLE);
                tvBack.setVisibility(View.VISIBLE);
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
//                tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
//                rlUser.setVisibility(View.VISIBLE);
//                rlWorkType.setVisibility(View.GONE);
//                rlendtime.setVisibility(View.GONE);
            } else if (5 == data.getOrderStatus()) {
                tvBack.setVisibility(View.GONE);
                tcTz.setText("");
                tcTz.setVisibility(View.VISIBLE);
//                presenter.meshState(orderBean);
                tvCz.setText("等待农机主确认归还");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
//                tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
//                rlUser.setVisibility(View.VISIBLE);
//                rlWorkType.setVisibility(View.GONE);
//                rlendtime.setVisibility(View.GONE);
            }else if (6 == data.getOrderStatus()){
                tvBack.setVisibility(View.GONE);
                tvCz.setText("已归还");
                tcTz.setText("");
                tvCz.setBackgroundResource(R.drawable.bg_radius_4_dd);
            }
        } else if (orderBean != null) {
            tvType.setText(orderBean.getMeshTypeName());
//            tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
            tvOwner.setText(orderBean.getMeshUserName());
            tvPhone.setText(orderBean.getMeshUserPhone());
            tvNumber.setText(orderBean.getMeshNum());
            tvWorkType.setText(orderBean.getWorkTypeName());
            tvendTime.setText(orderBean.getEndDate());
            if (0 == orderBean.getOrderStatus()) {
                tvCz.setText("已取消");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
            } else if (1 == orderBean.getOrderStatus()) {
                tvCz.setText("立即接单");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
//                tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
//                rlUser.setVisibility(View.GONE);
//                rlWorkType.setVisibility(View.VISIBLE);
//                rlendtime.setVisibility(View.VISIBLE);
            } else if (2 == orderBean.getOrderStatus()) {
                tvCz.setText("待移交");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
//                tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
//                rlUser.setVisibility(View.VISIBLE);
//                rlWorkType.setVisibility(View.GONE);
//                rlendtime.setVisibility(View.GONE);
            } else if (3 == orderBean.getOrderStatus()) {
                tvCz.setText("确认");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_dirver_3));
//                tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
//                rlUser.setVisibility(View.VISIBLE);
//                rlWorkType.setVisibility(View.GONE);
//                rlendtime.setVisibility(View.GONE);
            } else if (4 == orderBean.getOrderStatus()) {
                tvBack.setVisibility(View.VISIBLE);
                tcTz.setVisibility(View.VISIBLE);
                presenter.meshState(orderBean);
                tvCz.setText("申请加油");
                tcTz.setText("调整");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
//                tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
//                rlUser.setVisibility(View.VISIBLE);
//                rlWorkType.setVisibility(View.GONE);
//                rlendtime.setVisibility(View.GONE);
            } else if (5 == orderBean.getOrderStatus()) {
                tvBack.setVisibility(View.GONE);
                tcTz.setText("");
                tcTz.setVisibility(View.VISIBLE);
//                presenter.meshState(orderBean);
                tvCz.setText("等待农机主确认归还");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
//                tvUser.setText(UserService.getInstance().getUserInfoBean().getUserName());
//                rlUser.setVisibility(View.VISIBLE);
//                rlWorkType.setVisibility(View.GONE);
//                rlendtime.setVisibility(View.GONE);
            }else if (6 == orderBean.getOrderStatus()){
                tvBack.setVisibility(View.GONE);
                tvCz.setText("已归还");
                tcTz.setText("");
                tvCz.setBackgroundResource(R.drawable.bg_radius_4_dd);
            }
        }
        addFragment();
    }

    private void addFragment() {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); //去掉切换Fragment时闪动的动画效果
        transaction.replace(R.id.map_container, new CommonMapfragment());
        transaction.commitNowAllowingStateLoss();
    }

    @OnClick({R.id.common_back_iv, R.id.tv_caozuo, R.id.tv_back, R.id.tv_tz, R.id.iv_next})
    public void onCLick(View view) {
        switch (view.getId()) {
            case R.id.common_back_iv:
                onBackPressed();
                break;
            case R.id.tv_back:
                if ("取消调整".equals(tvBack.getText().toString())) {
                    rlOwner.setVisibility(View.VISIBLE);
                    rlReason.setVisibility(View.GONE);
                    tcTz.setText("调整");
                    tvCz.setText(lastStr);
                    if (orderBean!=null){
                        tvendTime.setText(orderBean.getEndDate());
                    }else if (data!=null){
                        tvendTime.setText(data.getEndDate());
                    }

                    ivNext.setVisibility(View.GONE);
                    tvBack.setText("归还设备");
                } else {
                    if ("申请加油".equals(tvCz.getText().toString())){
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("是否确定归还");
                        //点击对话框以外的区域是否让对话框消失
                        builder.setCancelable(true);
                        //设置正面按钮
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                progressBar.setVisibility(View.VISIBLE);
                                presenter.deviceGiveBack(data!=null?data.getOrderId():orderBean.getOrderId());

                            }
                        });
                        //设置反面按钮
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();

                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }else {
                        ToastUtils.showShort("当前有未完成的加油订单，暂无法归还");
                    }
                }

                break;
            case R.id.iv_next:
                chooseTime();
                break;
            case R.id.tv_tz:
                rlOwner.setVisibility(View.GONE);
                rlReason.setVisibility(View.VISIBLE);
                ivNext.setVisibility(View.VISIBLE);
                edReason.setText("");
                tcTz.setText("");
                tvBack.setText("取消调整");
                lastStr=tvCz.getText().toString();
                lastTime=tvendTime.getText().toString();
                tvCz.setText("确认提交");
                break;
            case R.id.tv_caozuo:
                if ("确认提交".equals(tvCz.getText().toString())) {
                    if (TextUtils.isEmpty(edReason.getText().toString())){
                        ToastUtils.showShort("请输入原因");
                        return;
                    }
                    if (lastTime.equals(tvendTime.getText().toString())){
                        ToastUtils.showShort("当前时间和修改前的时间相同");
                        return;
                    }
                    progressBar.setVisibility(View.VISIBLE);
                    presenter.updateFindDriverOrderDate(edReason.getText().toString(),orderBean!=null?orderBean.getOrderId():data.getOrderId(),tvendTime.getText().toString());
                    return;
                }
                if ("申请加油".equals(tvCz.getText().toString())) {
                    if (jiayouDIalog == null) {
                        jiayouDIalog = new JiayouDIalog(this);
                        jiayouDIalog.setJiaYouDialogHandleCallback(this);
                    }
                    jiayouDIalog.show();
                    jiayouDIalog.dirverUpdate();
                    return;
                }
                if (data != null) {
                    if (1 == data.getOrderStatus()) {
                        progressBar.setVisibility(View.VISIBLE);
                        data.setOrderStatus(2);
                        presenter.updateFindDriverOrder(data);
                    } else if (3 == data.getOrderStatus()) {
                        progressBar.setVisibility(View.VISIBLE);
                        data.setOrderStatus(4);
                        presenter.updateFindDriverOrder(data);
                    }
                } else if (orderBean != null) {
                    if (1 == orderBean.getOrderStatus()) {
                        progressBar.setVisibility(View.VISIBLE);
                        orderBean.setOrderStatus(2);
                        presenter.updateFindDriverOrder(orderBean);
                    } else if (3 == orderBean.getOrderStatus()) {
                        progressBar.setVisibility(View.VISIBLE);
                        orderBean.setOrderStatus(4);
                        presenter.updateFindDriverOrder(orderBean);
                    }
                }
                break;

        }
    }


    @Override
    public DirverDetailView getMvpView() {
        return this;
    }

    @Override
    public DirverDetailPresenter createPresenter() {
        return new DirverDetailPresenter();
    }

    @Override
    public void onError(String message) {
        ToastUtils.showShort(message);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showOrderList(List<DIrverOrderBean> results) {

    }

    @Override
    public void updateSuccess() {
        progressBar.setVisibility(View.GONE);
        ToastUtils.showShort("操作成功");
//        rlUser.setVisibility(View.VISIBLE);
//        rlWorkType.setVisibility(View.GONE);
//        rlendtime.setVisibility(View.GONE);
        if (data != null) {
            if (2 == data.getOrderStatus()) {
                tvCz.setText("待移交");
                EventBus.getDefault().post(new JieDanEvent());
            } else if (4 == data.getOrderStatus()) {
                tvCz.setText("申请加油");
                tcTz.setText("调整");
                tvBack.setVisibility(View.VISIBLE);
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
            }
        } else if (orderBean != null) {
            if (2 == orderBean.getOrderStatus()) {
                tvCz.setText("待移交");
                EventBus.getDefault().post(new JieDanEvent());
            } else if (4 == orderBean.getOrderStatus()) {
                tvCz.setText("申请加油");
                tcTz.setText("调整");
                tvBack.setVisibility(View.VISIBLE);
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
            }
        }
    }

    @Override
    public void meshStatus(OilOrderState o) {
        if (o == null || o.getLastOilRequest() == null) {
            return;
        }
        if (o.getLastOilRequest() != null) {
            OilOrderState.LastOilRequestBean lastOilRequestBean = o.getLastOilRequest();
            if ("submit".equals(lastOilRequestBean.getRequestState())){
                tvCz.setText("加油申请待农机主确认");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
                return;
            }
            if ("refuse".equals(lastOilRequestBean.getRequestState())){
                tvCz.setText("申请加油");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_blue));
                return;
            }
            if ("waiting".equals(lastOilRequestBean.getOrderState())) {
                tvCz.setText("等待接单中");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
            } else if ("confirmed".equals(lastOilRequestBean.getOrderState())) {
                tvCz.setText("等待加油车到来");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
            } else if ("arrived".equals(lastOilRequestBean.getOrderState())) {
                tvCz.setText("加油车已到达");
                tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
            }
        }
    }

    @Override
    public void SqSuccess() {
        progressBar.setVisibility(View.GONE);
        tvCz.setText("加油申请待农机主确认");
        tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
    }

    @Override
    public void showUpdateSuccess() {
        progressBar.setVisibility(View.GONE);
        ToastUtils.showShort("调整申请已发送，请等待农机主确认");
        rlOwner.setVisibility(View.VISIBLE);
        rlReason.setVisibility(View.GONE);
        tcTz.setText("调整");
        tvCz.setText(lastStr);
        tvBack.setText("归还设备");
        ivNext.setVisibility(View.GONE);

    }

    @Override
    public void giveBackSuccess() {
        progressBar.setVisibility(View.GONE);
        ToastUtils.showShort("归还请求已提交，待农机主确认");
        tvBack.setVisibility(View.GONE);
        tcTz.setText("");
        tcTz.setVisibility(View.VISIBLE);
//        presenter.meshState(orderBean);
        tvCz.setText("等待农机主确认归还");
        tvCz.setBackground(getResources().getDrawable(R.drawable.bg_radius_4_dd));
    }

    @Override
    public void JiaYouOk(NjBean njBean, String phone, String address, String count) {
        progressBar.setVisibility(View.VISIBLE);
        presenter.createRequest(orderBean.getMeshId() + "", count,currentPos,address);
    }

    @Override
    public void chooseAera() {
        startActivityForResult(new Intent(this, ChooseAeraActivity.class),102);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==144&&data!=null){
            PoiItem poiItem=data.getParcelableExtra("pos");
            if (poiItem!=null){
                currentPos=poiItem;
                if (jiayouDIalog!=null&&jiayouDIalog.isShowing()){
                    jiayouDIalog.dirverUpdate(poiItem);
                }
            }
        }else if (resultCode==244&&data!=null){
            boolean isnow=data.getBooleanExtra("loc",false);
            if (isnow){
                if (jiayouDIalog!=null&&jiayouDIalog.isShowing()){
                    jiayouDIalog.dirverUpdateLocation();
                }
            }
        }
    }

    private void chooseTime() {
        Calendar calendar = Calendar.getInstance();
       DatePickerDialog datePickerDialog= new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

                String monthStr;
                if (month < 9) {
                    monthStr = "0" + (month + 1);
                } else {
                    monthStr = (month + 1) + "";
                }

                tvendTime.setText(year + "-" + monthStr + "-" + dayOfMonth);

            }
        },

                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.getDatePicker().setMinDate(new Date().getTime());
        datePickerDialog.show();

    }
}
